package com.mao.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mao.common.BaseContext;
import com.mao.common.CustomException;
import com.mao.dto.OrdersDto;
import com.mao.entity.*;
import com.mao.mapper.OrdersMapper;
import com.mao.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
@Slf4j
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
   @Autowired
   private AddressBookService addressBookService;

   @Autowired
   private UserService userService;

   @Autowired
   private OrderDetailService orderDetailService;

   @Autowired
   private ShoppingCartService shoppingCartService;

    /**
     * 用户下单
     * @param orders
     */
    @Override
    @Transactional
    public void submit(Orders orders) {
        //获取当前用户id
        Long userId = BaseContext.getCurrentId();

        //查询用户数据
        User user = userService.getById(userId);

        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(queryWrapper);
        if (shoppingCartList == null || shoppingCartList.size()==0){
            throw new CustomException("购物车是空的，不能下单");
        }

        //查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook==null){
            throw new CustomException("地址为空，请先添加地址");
        }

        long orderId = IdWorker.getId();//订单id
        //向订单明细表插入数据，多条数据
        AtomicInteger amount = new AtomicInteger(0);
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setName(item.getName());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        orderDetailService.saveBatch(orderDetailList);

        //向订单表插入数据，一条数据
       orders.setId(orderId);
       orders.setOrderTime(LocalDateTime.now());
       orders.setCheckoutTime(LocalDateTime.now());
       orders.setStatus(2);
       orders.setUserId(userId);
       orders.setAmount(new BigDecimal(amount.get()));
       orders.setNumber(String.valueOf(orderId));
       orders.setUserName(addressBook.getConsignee());//暂时改成addressBook.getConsignee()
       orders.setConsignee(addressBook.getConsignee());
       orders.setPhone(addressBook.getPhone());
       orders.setAddress((addressBook.getProvinceName()==null ? "":addressBook.getProvinceName())
       +(addressBook.getCityName()==null ? "":addressBook.getCityName())
       +(addressBook.getDistrictName()==null ? "" : addressBook.getDistrictName())
       +(addressBook.getDetail()==null ? "" :addressBook.getDetail()));

       this.save(orders);

        //最后清空购物车数据
        shoppingCartService.remove(queryWrapper);
    }

    /**
     * 获取订单的明细信息
     * @param orderId
     * @return
     */
    public List<OrderDetail> getOrderDetails(Long orderId){
        LambdaQueryWrapper<OrderDetail> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,orderId);
        List<OrderDetail> orderDetails = orderDetailService.list(queryWrapper);
        return orderDetails;
    }

    @Override
    public Page<OrdersDto> userToOrders(int page, int pageSize) {
        log.info("page={},pageSize={}",page,pageSize);
        Long userID = BaseContext.getCurrentId();
        Page<Orders> ordersPage=new Page<>(page,pageSize);
        Page<OrdersDto> ordersDtoPage=new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId,userID);
        queryWrapper.orderByDesc(Orders::getOrderTime);
        this.page(ordersPage,queryWrapper);
        List<Orders> records = ordersPage.getRecords();
        List<OrdersDto> ordersDtos = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            List<OrderDetail> orderDetails = this.getOrderDetails(item.getId());
            ordersDto.setOrderDetails(orderDetails);
            return ordersDto;
        }).collect(Collectors.toList());
        BeanUtils.copyProperties(ordersPage,ordersDtoPage,"records");
        ordersDtoPage.setRecords(ordersDtos);
        return ordersDtoPage;
    }

    /**
     * 后台查询订单
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public Page<Orders> page(int page, int pageSize, Long number, String beginTime, String endTime) {
        Page<Orders> ordersPage=new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(number!=null,Orders::getNumber,number)
                .gt(StringUtils.isNotEmpty(beginTime),Orders::getOrderTime,beginTime)
                .lt(StringUtils.isNotEmpty(endTime),Orders::getOrderTime,endTime);
        this.page(ordersPage,queryWrapper);
        return ordersPage;
    }

    /**
     * 后台操作订单
     * @param orders
     */
    @Override
    public void Modify_the_order( Orders orders) {
        LambdaUpdateWrapper<Orders> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Orders::getId,orders.getId());
        lambdaUpdateWrapper.set(Orders::getStatus,orders.getStatus());
        this.update(lambdaUpdateWrapper);
    }


    /**
     * 再来一单
     * @param orders
     */
    @Override
    public void add_one_order(Orders orders) {
        //1.获取用户id
        Long userId = BaseContext.getCurrentId();
        //2.获取订单id
        Long ordersId = orders.getId();
        //3.根据订单id查询订单明细
        LambdaQueryWrapper<OrderDetail> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,ordersId);
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);
        //4.将订单明细数据放入购物车
        List<ShoppingCart> shoppingCarts = orderDetailList.stream().map((item) -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setImage(item.getImage());
            shoppingCart.setName(item.getName());
            if (item.getDishId() != null) {
                shoppingCart.setDishId(item.getDishId());
                shoppingCart.setDishFlavor(item.getDishFlavor());
            } else {
                shoppingCart.setSetmealId(item.getSetmealId());
            }
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartService.saveBatch(shoppingCarts);
    }


}
